// src/main/java/com/bookmanager/controller/LogoutController.java
package com.bookmanager.controller;

import jakarta.servlet.*;
import jakarta.servlet.http.*;
import jakarta.servlet.annotation.*;
import java.io.IOException;

@WebServlet("/logout")
public class LogoutController extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("=== 退出登录处理开始 ===");
        System.out.println("🔍 请求URI: " + request.getRequestURI());
        System.out.println("🔍 上下文路径: " + request.getContextPath());
        System.out.println("🔍 Servlet路径: " + request.getServletPath());
        System.out.println("🔍 完整URL: " + request.getRequestURL());

        // 获取当前session
        HttpSession session = request.getSession(false);

        if (session != null) {
            // 获取用户信息用于日志
            Object user = session.getAttribute("user");
            if (user != null) {
                System.out.println("✅ 用户退出登录: " + user.toString());
            } else {
                System.out.println("ℹ️ Session中未找到用户信息");
            }

            // 使session失效
            session.invalidate();
            System.out.println("✅ Session已失效");
        } else {
            System.out.println("ℹ️ 没有找到有效的Session");
        }

        // 重定向到登录页面
        String redirectPath = request.getContextPath() + "/login.jsp";
        System.out.println("🔄 重定向到: " + redirectPath);
        System.out.println("=== 退出登录处理结束 ===");

        response.sendRedirect(redirectPath);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}